#include "musicslider.h"
#include "ui_musicslider.h"
#include <QMouseEvent>

MusicSlider::MusicSlider(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicSlider)
{
    ui->setupUi(this);
    // 不能使用初始化列表，因为要先构建，才有 this->width()，不然会是随机值
    maxWidth = this->width();

    currentPos = 0;
    moveSlider();
}

MusicSlider::~MusicSlider()
{
    delete ui;
}

void MusicSlider::mouseMoveEvent(QMouseEvent *event)
{
    // 检测是否在这个范围内进行的点击，如果不在就返回
    QRect musicSliderRect = QRect(0,0,this->geometry().width(), this->geometry().height());
    if(!musicSliderRect.contains(event->pos())) return;

    if(event->buttons() == Qt::LeftButton)
    {
        currentPos = event->pos().x();
        currentPos = currentPos < 0 ? 0 : currentPos;
        currentPos = currentPos > maxWidth ? maxWidth : currentPos;
        moveSlider();
    }
}

void MusicSlider::mousePressEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();
}

void MusicSlider::mouseReleaseEvent(QMouseEvent *event)
{
    currentPos = event->pos().x();
    moveSlider();

    // 改变了进度条的位置之后，需要同步时间
    emit MusicSliderChanged(currentPos / (float)maxWidth);
}

void MusicSlider::moveSlider()
{
    ui->outLine->setGeometry(ui->outLine->x(), ui->outLine->y(), currentPos, ui->outLine->height());
}

void MusicSlider::setStep(float ration)
{
    currentPos = maxWidth * ration;
    moveSlider();
}
